<template>
  <div class="main">
    <!-- 数据查询区：表单 -->
    <el-form ref="queryRef" :model="queryParams" :inline="true">
      <el-form-item label="房间号" prop="roomNumber">
        <el-input
          v-model.number="queryParams.roomNumber"
          placeholder="请输入房间号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房型" prop="roomTypeId">
        <el-select
          v-model="queryParams.roomTypeId"
          style="width: 250px"
          placeholder="请选择房型"
          @change="handleQuery"
        >
          <el-option
            v-for="item in roomTypesOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="queryParams.status" @change="handleQuery">
          <el-radio-button label="空闲" />
          <el-radio-button label="已预定" />
          <el-radio-button label="已入住" />
          <el-radio-button label="打扫中" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-input
          v-model.number="queryParams.floor"
          placeholder="请输入楼层"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="面积" prop="area">
        <el-input
          v-model.number="queryParams.area"
          placeholder="请输入面积"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="朝向" prop="towards">
        <el-radio-group
          v-model="queryParams.towards"
          style="width: 200px"
          @change="handleQuery"
        >
          <el-radio-button label="东" />
          <el-radio-button label="南" />
          <el-radio-button label="西" />
          <el-radio-button label="北" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否有窗" prop="windows">
        <el-radio-group v-model="queryParams.windows" @change="handleQuery">
          <el-radio label="是">是</el-radio>
          <el-radio label="否">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据操作区：按钮 -->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          v-perms="['hotel:room:add']"
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-perms="['hotel:room:edit']"
          type="success"
          plain
          icon="Edit"
          :disabled="!single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-perms="['hotel:room:delete']"
          type="danger"
          plain
          icon="Delete"
          :disabled="!multiple"
          @click="handleDeleteBatch"
          >批量删除</el-button
        >
      </el-col>
    </el-row>
    <br />
    <!-- 数据展示区：表格 -->
    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" width="80" prop="id" />
      <el-table-column
        label="房间号"
        align="center"
        width="100"
        prop="roomNumber"
      />
      <el-table-column label="房型" align="center" width="150" prop="name" />
      <el-table-column
        label="基础价格"
        align="center"
        width="100"
        prop="basicPrice"
      />
      <el-table-column label="状态" align="center" width="100" prop="status">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.status)">{{
            scope.row.status
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="楼层" align="center" width="80" prop="floor" />
      <el-table-column label="面积" align="center" width="80" prop="area" />
      <el-table-column label="朝向" align="center" width="80" prop="towards" />
      <el-table-column
        label="是否有窗"
        align="center"
        width="80"
        prop="windows"
      />
      <el-table-column label="房间描述" align="center" prop="description" />
      <el-table-column
        label="操作"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            v-perms="['hotel:room:edit']"
            link
            type="primary"
            icon="Edit"
            size="large"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <!-- <el-button
            link
            type="primary"
            icon="Delete"
            size="small"
            @click="handleDelete(scope.row)"
            >删除</el-button
          > -->
          <el-button
            link
            type="primary"
            icon="View"
            size="large"
            @click="handleView(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 数据展示区：分页加载 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      style="margin-top: 20px"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 数据编辑区：新增/修改对话框 默认不显示 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="form.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model.number="form.floor" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input v-model.number="form.area" placeholder="请输入面积" />
        </el-form-item>
        <el-form-item label="是否有窗" prop="windows">
          <el-radio-group v-model="form.windows">
            <el-radio label="是">是</el-radio>
            <el-radio label="否">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="isEditing" label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio-button label="空闲" />
            <el-radio-button label="已预定" />
            <el-radio-button label="已入住" />
            <el-radio-button label="打扫中" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="朝向" prop="towards">
          <el-radio-group v-model="form.towards">
            <el-radio-button label="东" />
            <el-radio-button label="南" />
            <el-radio-button label="西" />
            <el-radio-button label="北" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="房型" prop="roomTypeId">
          <el-select v-model="form.roomTypeId" placeholder="请选择房型">
            <el-option
              v-for="item in roomTypesOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="2"
            placeholder="请输入房间描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)"
            >确 定</el-button
          >
          <el-button v-show="form.id === undefined" @click="resetForm(formRef)"
            >重 置</el-button
          >
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer
      v-model="drawer"
      title="产品信息"
      :with-header="false"
      size="50%"
    >
      <el-descriptions :title="roomTitle" :column="2" border>
        <el-descriptions-item label="房间号">{{
          room.roomNumber
        }}</el-descriptions-item>
        <el-descriptions-item label="房型">{{
          room.name
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{
          room.status
        }}</el-descriptions-item>
        <el-descriptions-item label="楼层">{{
          room.floor
        }}</el-descriptions-item>
        <el-descriptions-item label="面积">{{
          room.area
        }}</el-descriptions-item>
        <el-descriptions-item label="朝向">{{
          room.towards
        }}</el-descriptions-item>
        <el-descriptions-item label="是否有窗">{{
          room.windows
        }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{
          room.type
        }}</el-descriptions-item>
        <el-descriptions-item label="等级">{{
          room.level
        }}</el-descriptions-item>
        <el-descriptions-item label="床位">{{
          room.beds
        }}</el-descriptions-item>
        <el-descriptions-item label="基础价格">{{
          room.basicPrice
        }}</el-descriptions-item>
        <el-descriptions-item label="图片">
          <img :src="room.image" style="width: 300px; height: 300px" />
        </el-descriptions-item>

        <el-descriptions-item label="房间描述">{{
          room.description
        }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
/** ------------------全局导入区-------------------- */
import { ref, reactive, toRef, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { listAllRoomTypes } from "@/api/roomtypes";
import {
  listAllRooms,
  listRoomsByPage,
  getRoomById,
  addRoom,
  updateRoom,
  deleteRoomsBatch
} from "@/api/rooms";
import type {
  RoomTypesDTO,
  QueryParams,
  RoomsDTO,
  RoomForm
} from "@/api/rooms";

onMounted(() => {
  // 挂载后加载数据
  getList();
  getRoomTypesOptions();
});

/** ------------------数据查询区——表单-------------------- */
// 表单实例
const queryRef = ref<FormInstance>();

// 类别下拉框
const roomTypesOptions = ref<RoomTypesDTO[]>([]);

function getRoomTypesOptions() {
  listAllRoomTypes().then(response => {
    roomTypesOptions.value = response.data;
  });
}

// 查询
const query = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 5,
  roomNumber: undefined,
  area: undefined,
  floor: undefined,
  status: undefined,
  windows: undefined,
  towards: undefined,
  roomTypeId: undefined
});
const queryParams = toRef(query);
// 数据查询区--> 查询按钮
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
// 数据查询区--> 重置按钮
const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  getList();
};

/** ------------------数据展示区——表格-------------------- */

// 数据列表
const loading = ref<boolean>(false); // table数据加载遮罩
const total = ref<number>(0); // table数据总数
const tableData = reactive<RoomsDTO[]>([]); // table数据
const dataList = toRef(tableData);

// 数据展示区--> 数据加载
function getList() {
  loading.value = true;
  /** 调用后端分页查询接口 */
  listRoomsByPage(queryParams.value).then(response => {
    dataList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}

function getTagType(status) {
  if (status === "空闲") return "success";
  if (status === "已预定") return "warning";
  if (status === "已入住") return "danger";
  if (status === "打扫中") return "primary";
}

/** ------------------数据展示区：数据选择-------------------- */

const ids = ref<number[]>([]); // 表单勾选的id
const single = ref<boolean>(false); // 勾选1个
const multiple = ref<boolean>(false); // 勾选多个

// 数据展示区--> 勾选数据
function handleSelectionChange(selection: RoomsDTO[]) {
  ids.value = selection.map((item: RoomsDTO) => item.id);
  single.value = selection.length == 1;
  multiple.value = selection.length >= 1;
}

/** ------------------数据展示区：分页加载-------------------- */
// 分页--> 修改每页数据数（5｜10｜20｜30）
function handleSizeChange(val: number) {
  queryParams.value.pageSize = val;
  getList();
}

//分页--> 修改当前页
function handleCurrentChange(val: number) {
  queryParams.value.pageNum = val;
  getList();
}

/** ------------------数据编辑区——对话框+表单-------------------- */
// 表单数据
const formRef = ref<FormInstance>();

const formData = reactive<RoomForm>({
  id: undefined,
  roomNumber: undefined,
  status: undefined,
  floor: undefined,
  area: undefined,
  windows: undefined,
  towards: undefined,
  roomTypeId: undefined,
  description: undefined
});
const form = toRef(formData);
const rules = reactive<FormRules<RoomForm>>({
  // 表单验证规则
  roomNumber: [
    { required: true, message: "房间号不能为空", trigger: "blur" },
    { min: 3, max: 10, message: "长度在3-10 个字符", trigger: "blur" }
  ],
  floor: [
    { required: true, message: "楼层不能为空", trigger: "blur" },
    { type: "number", message: "楼层必须为数字值", trigger: "blur" }
  ],
  area: [
    { required: true, message: "面积不能为空", trigger: "blur" },
    { type: "number", message: "面积必须为数字值", trigger: "blur" }
  ],
  windows: [{ required: true, message: "是否有窗不能为空", trigger: "blur" }],
  towards: [{ required: true, message: "朝向不能为空", trigger: "blur" }],
  // status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
  roomTypeId: [{ required: true, message: "房型不能为空", trigger: "blur" }]
});

// 对话框数据
const title = ref(""); // 对话框标题
const open = ref(false); //对话框打开
const isEditing = ref(false);

// 数据编辑区-->提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      /** 调用后端新增和修改接口 */
      if (form.value.id != undefined) {
        updateRoom(form.value).then(response => {
          ElMessage({ type: "success", message: "修改数据成功" });
          getList();
          open.value = false;
        });
      } else {
        addRoom(form.value).then(response => {
          ElMessage({ type: "success", message: "新增数据成功" });
          getList();
          open.value = false;
        });
      }
    } else {
      console.log("表单验证未通过", fields); // 前台会自动提示errors
    }
  });
};

// 数据编辑区-->重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 数据编辑区-->取消按钮
function cancel() {
  initForm();
  open.value = false;
}

/** ------------------数据操作区——按钮-------------------- */
// 清空或赋值表单数据
const initForm = () => {
  formRef.value?.resetFields();
  form.value = { ...formData };
  console.log(form.value);
};

// 数据操作区--> 新增按钮
function handleAdd() {
  initForm();
  title.value = "新增数据";
  open.value = true;
  isEditing.value = false;
  form.value.status = null;
}

// 数据操作区区--> 修改按钮
function handleUpdate(row: any) {
  initForm();
  const id = row.id || ids.value[0];
  isEditing.value = true;
  /** 调用后端id查询接口*/

  getRoomById(id).then(response => {
    console.log(response.data);
    form.value = response.data;
    title.value = "修改数据[" + id + "]";
    open.value = true;
  });
}

// 数据操作区--> 删除按钮
// function handleDelete(row: any) {
//   const id = row.productId;
//   ElMessageBox.confirm("是否删除编号为" + id + "的数据?", "警告")
//     .then(() => {
//       return deleteProduct(id);
//     })
//     .then(() => {
//       getList();
//       ElMessage({ type: "success", message: "删除成功" });
//     })
//     .catch(() => {});
// }

// 数据操作区--> 批量删除按钮
function handleDeleteBatch() {
  const roomsIds = ids.value;
  ElMessageBox.confirm("是否批量删除编号为" + roomsIds + "的数据?", "警告")
    .then(() => {
      return deleteRoomsBatch(roomsIds);
    })
    .then(() => {
      getList();
      ElMessage({ type: "success", message: "批量删除成功" });
    })
    .catch(() => {});
}

// 数据操作区-->抽屉查看数据
const drawer = ref<boolean>(false);
const roomTitle = ref<string>("");
const room = ref<RoomsDTO>({
  id: 0,
  roomNumber: "",
  floor: 0,
  status: "",
  area: 0,
  windows: "",
  towards: "",
  description: "",
  roomTypeId: 0,
  name: "",
  image: "",
  type: "",
  level: "",
  beds: 0,
  basicPrice: 0
});

// 数据操作区--> 查看按钮
function handleView(row: RoomsDTO) {
  // product.value = row
  getRoomById(row.id).then(response => {
    room.value = response.data;
    roomTitle.value = "查看房间数据[" + row.id + "]";
  });
  drawer.value = true;
}
</script>
